var mqtt = require('mqtt')
var MqttClient= mqtt.connect('mqtt://127.0.0.1:1883')
const linkList = [] // 长连接的列表
MqttClient.linkState = true // 这里是自定义的长连接状态

// 连接成功
MqttClient.on("connect", () => {
        MqttClient.linkState = true // 改变连接状态
        const linkArr = Object.values(MqttClient.messageIdToTopic)
        
        linkList.forEach(item => {
            if(!linkArr.includes(item)) {
                MqttClient.subscribe(item)
            }
        })

    })    

// 链接报错
MqttClient.on("error", () => {
   MqttClient.linkState = false
})


    // 链接断开
MqttClient.on("close", () => {
    MqttClient.linkState = false
})
        
// 添加主题
export function AddLink(link){
    // 当连接中 直接订阅 
    if(MqttClient.linkState) {
        MqttClient.subscribe(link)
    }
    // 简单地去重
    if(!linkList.includes(link)) linkList.push(link)   
}

// 删除取消主题
export function DeleteLink(arr) {
    arr.forEach(item => {
        const key = linkList.findIndex(link => link === item)
        if(key >= 0) {
            linkList.splice(key,1)
            MqttClient.unsubscribe(item)
        }
    })
} 
// 回调消息
export function MyMqttMsg(Callback) {

    MqttClient.on("message", (topic, res) => {
       
        Callback(JSON.parse(res))
    })
}